package cn.icatw.leetcode.editor.cn;
//给定一个二叉树的根节点 root ，和一个整数 targetSum ，求该二叉树里节点值之和等于 targetSum 的 路径 的数目。
//
// 路径 不需要从根节点开始，也不需要在叶子节点结束，但是路径方向必须是向下的（只能从父节点到子节点）。
//
//
//
// 示例 1：
//
//
//
//
//输入：root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
//输出：3
//解释：和等于 8 的路径有 3 条，如图所示。
//
//
// 示例 2：
//
//
//输入：root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
//输出：3
//
//
//
//
// 提示:
//
//
// 二叉树的节点个数的范围是 [0,1000]
//
// -10⁹ <= Node.val <= 10⁹
// -1000 <= targetSum <= 1000
//
//
// Related Topics 树 深度优先搜索 二叉树 👍 1876 👎 0


import java.util.HashMap;
import java.util.Map;

//Java：路径总和 III
public class T437_PathSumIii {
    public static void main(String[] args) {
        Solution solution = new T437_PathSumIii().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public int pathSum(TreeNode root, int targetSum) {
            if (root == null) {
                return 0;
            }
            //    使用哈希表记录前缀和出现的次数
            Map<Long, Integer> prefixSumCount = new HashMap<>();
            //    初始情况，前缀和为0，出现次数为1
            prefixSumCount.put(0L, 1);
            return recursionPathSum(root, prefixSumCount, targetSum, 0L);
        }

        private int recursionPathSum(TreeNode node, Map<Long, Integer> prefixSumCount, int targetSum, Long currentSum) {
            if (node == null) {
                return 0;
            }
            //更新当前路径的前缀和
            currentSum += node.val;
            //获取路径为target的数量
            int count = prefixSumCount.getOrDefault(currentSum - targetSum, 0);
            //更新当前路径的前缀和出现的次数
            prefixSumCount.put(currentSum, prefixSumCount.getOrDefault(currentSum, 0) + 1);
            //递归左右子树
            count += recursionPathSum(node.left, prefixSumCount, targetSum, currentSum);
            count += recursionPathSum(node.right, prefixSumCount, targetSum, currentSum);
            //回溯，删除当前路径的前缀和
            prefixSumCount.put(currentSum, prefixSumCount.get(currentSum) - 1);
            return count;
        }
    }


    //leetcode submit region end(Prohibit modification and deletion)
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
